#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Replace URI's with absolute URI's calculated relative to the context from where
they are created. This is relative to the .page file from where they are printed.
"""

import xml.dom.minidom
from seagull import url_translations

def _resolve_urls(node, reference_path):
	for n in node.childNodes:
		if n.nodeType == n.ELEMENT_NODE:
			# Replace URIs
			if n.localName in ('a', 'link') and n.hasAttribute('href'):
				href = n.getAttribute('href')
				href = url_translations.page_to_url(href, reference_page=reference_path)
				n.setAttribute('href', href)
			elif n.localName in ('img', 'script') and n.hasAttribute('src'):
				src = n.getAttribute('src')
				src = url_translations.page_to_url(src, reference_page=reference_path)
				n.setAttribute('src', src)

			# Recursive
			if n.localName == 'placeholder' and n.prefix == 'pp':
				# <pp:placeholder url-base="...">...</pp:placeholder>
				_resolve_urls(n, n.getAttribute('url-base'))
			else:
				_resolve_urls(n, reference_path)

def execute_minidom(server, document, parameters):
	_resolve_urls(document, '/')
